<script setup>
import { message } from 'ant-design-vue'
import aiApi from '@/api/ai/aiApi'
import aiChatApi from '@/api/ai/aiChatApi'
import aiChatHistoryApi from '@/api/ai/aiChatHistoryApi'
import { nanoid } from "nanoid";
import { h } from 'vue';
import { SendOutlined } from '@ant-design/icons-vue';
import AiEngine from './engine.js';
import tool from '@/utils/tool'

const keywords = ref();
let ai = null;
onMounted(async () => {
	//workflowEngine
	await queryEnableAiConfig();
	queryHistoryList();

	if(!aiConfig.value){
		message.error("没有找到启用的AI配置");
		return;
	}
	ai = new AiEngine(aiConfig.value.url,
		aiConfig.value.aiChatConfig.urlTemplateConfig,
		aiConfig.value.aiChatConfig.headerTemplateConfig,
		aiConfig.value.aiChatConfig.templateConfig,
		aiConfig.value.aiChatConfig.responseTemplateConfig,
		{
			...aiConfig.value.aiChatConfig,
			...aiConfig.value
		},
		sendMessage,
		updateMessage
	);
})


const problemList = ref([

])

const pressEnter = () => {
	if (!aiConfig.value) {
		message.error("获取ai配置失败，无法使用小助手！")
		return
	}

	if (!keywords.value) {
		message.warn("你没有输入任何东西")
		return
	}
	const problem = {
		id: nanoid(5),
		role: "user",
		message: keywords.value
	};
	saveProblem(problem);

	//开始进行ai问答
	problemList.value.push(problem);

	keywords.value = "";

	// if (!aiModal.value) {
	ai.startConnect();
	// }

}
let currentId = null;

const updateMessage = (type, message) => {
	if (type == 'start') {
		currentId = nanoid(5);
		problemList.value.push({
			id: currentId,
			role: "ai",
			message: message
		});
	} else if (type == 'active') {
		updateProblemById(currentId, message);
	} else if (type == 'end') {

		let b = updateProblemById(currentId, message);
		saveProblem(b);
		currentId = null;
	}
}
const queryHistoryList = async () => {
	const data = await aiChatHistoryApi.getByAiChatId({
		aiChatId: aiConfig.value.aiChatConfig.id
	});

	problemList.value = [];

	problemList.value.push({
		id: nanoid(5),
		role: "ai",
		message: "请问有什么能帮助您的？"
	})

	for (const dd of data) {
		problemList.value.push({
			id: dd.id,
			role: dd.role,
			message: dd.content
		})
	}

}

const saveProblem = (p) => {

	aiChatHistoryApi.batchSave([{
		content: p.message,
		role: p.role,
		aiId: aiConfig.value.id,
		aiChatId: aiConfig.value.aiChatConfig.id
	}]);
}



const updateProblemById = (id, message) => {
	let current = null;
	for (let problem of problemList.value) {
		if (problem.id == id) {
			problem.message = problem.message + message;
			current = problem;
			break;
		}
	}
	return current;
}



const sendMessage = async () => {
	const templateConfig = aiConfig.value.aiChatConfig.templateConfig;
	const userInfo = tool.data.get('USER_INFO');

	// let historys = await aiChatHistoryApi.getByAiChatId({
	// aiChatId: aiConfig.value.aiChatConfig.id
	// })

	let size = problemList.value.length;

	let i = 0;
	let historys = [];
	//只记录前10条
	for (let ib of problemList.value) {
		if (size - i > 10) {
			i++;
			continue;
		}
		historys.push({
			role: ib.role == 'ai' ? 'assistant' : ib.role,
			content: ib.message
		})

		i++;

	}


	let tc = await aiChatApi.resolveTemplateConfig({
		"template": templateConfig,
		data: {
			...aiConfig.value,
			"uid": userInfo.id,
			historys: historys || []
		}
	})
	console.log(tc)
	tc = tc.replace(/\n/g, "");
	return tc;
}

const aiConfig = ref();

const queryEnableAiConfig = async () => {
	const cbd = await aiApi.list({
		disableFlag: 0
	});

	if (!cbd || cbd.length <= 0) {
		return
	}
	aiConfig.value = cbd[0];
	//获取chat配置
	const aiChatConfig = await aiChatApi.getByAiId({
		aiId: aiConfig.value.id
	});
	aiConfig.value.aiChatConfig = aiChatConfig;
}

const resetHistory = async () => {
	await aiChatHistoryApi.clearHistory({
		aiChatId: aiConfig.value.aiChatConfig.id
	});
	queryHistoryList();
}
</script>

<template>
	<div style="height: 90%;overflow-x: scroll;" class="mb-2">
		<a-row v-for="(item, index) in problemList" :key="index" style="margin-top: 10px;">
			<a-col :span="24" v-if="item.role == 'ai'">
				<BulbOutlined />
				<span>
					:
				</span>
				<a-tag color="green">{{ item.message }}</a-tag>
			</a-col>

			<a-col :span="24" v-if="item.role == 'user'">
				<a-flex justify="flex-end" align="start">
					<a-row>
						<a-tag color="blue">{{ item.message }}</a-tag>
						<span>
							:
						</span>
						<QuestionCircleOutlined />
					</a-row>
				</a-flex>
			</a-col>
		</a-row>
	</div>
	<div>
		<a-row>

			<a-col :span="15">
				<a-input @pressEnter="pressEnter" v-model:value="keywords" placeholder="请输入问题"></a-input>
			</a-col>

			&nbsp; &nbsp;

			<a-col :span="3">
				<a-button type="primary" :icon="h(SendOutlined)" @click="pressEnter">发送</a-button>
			</a-col>

			&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

			<a-col :span="2">
				<a-button @click="resetHistory">重置</a-button>
			</a-col>
		</a-row>
	</div>
</template>




<style scoped lang="less">
.ant-tag {
	white-space: break-spaces
}
</style>
